import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import '../../base/Constant.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../util/LoadingUtil.dart';
import '../../util/SignUtil.dart';

class IdentityPage extends StatefulWidget {
  IdentityPage({Key key}) : super(key: key);

  @override
  _IdentityPage createState() => _IdentityPage();
}

class _IdentityPage extends State<IdentityPage> {
  Asset phont1, photo2;
  String token = "", name = "", number = "";
  @override
  void initState() {
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          title: new Text(
            "实名认证",
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black),
          ),
          elevation: 0.2,
          backgroundColor: Colors.white,
          brightness: Brightness.light,
          centerTitle: true,
          iconTheme: new IconThemeData(color: Colors.black),
        ),
        body: SingleChildScrollView(
          child: Container(
            width: double.infinity,
            child: new Column(
              children: <Widget>[
                GestureDetector(
                  child:Container(
                    padding: EdgeInsets.fromLTRB(0, kMargin20, 0, kMargin20),
                    width:ScreenUtil.getInstance().setWidth(750)-kMargin20*2,
                    color: white,
                     margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                    child: phont1 == null
                      ? Image.asset(
                          "images/pay_shenfenzheng_zheng.png",
                          width: (ScreenUtil.getInstance().setWidth(750)-kMargin10)/ 2,
                          height: (MediaQuery.of(context).size.width - 30) /
                              2 /
                              1.585,
                          // fit: BoxFit.fill,
                        )
                      : AssetThumb(
                          asset: phont1,
                          width: ((ScreenUtil.getInstance().setWidth(750)-kMargin10)/ 2)
                              .floor(),
                          height: ((MediaQuery.of(context).size.width - 30) /
                                  2 /
                                  1.585)
                              .floor(),
                        ),
                  ) ,
                  onTap: () {
                    selPhoto1();
                  },
                ),
                GestureDetector(
                  onTap: () {
                    selPhoto2();
                  },
                  child:Container(
                    width:ScreenUtil.getInstance().setWidth(750)-kMargin20*2,
                    color: white,
                    margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                    padding: EdgeInsets.fromLTRB(0, kMargin20, 0, kMargin20),
                    child:photo2 == null
                      ? Image.asset(
                          "images/pay_shenfenzhzeng_fan.png",
                          width: (ScreenUtil.getInstance().setWidth(750)-kMargin10)/ 2,
                          height: (MediaQuery.of(context).size.width - 30) /
                              2 /
                              1.585,
                          // fit: BoxFit.fill,
                        )
                      : AssetThumb(
                          asset: photo2,
                          width: ((ScreenUtil.getInstance().setWidth(750)-kMargin10)/ 2)
                              .floor(),
                          height: ((MediaQuery.of(context).size.width - 30) /
                                  2 /
                                  1.585)
                              .floor(),
                        ),
                  ) 
                ),
                Container(
                 
                  child: Image.asset('images/yaoqiu.png', width:ScreenUtil.getInstance().setWidth(750)-kMargin20*2,fit: BoxFit.fill,),
                ),
                // Padding(
                //   padding:
                //       EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
                //   child: Text(
                //     '请填写您的真实信息，通过后不可更改',
                //     style: TextStyle(
                //         color: black,
                //         fontSize:
                //             ScreenUtil.getInstance().setSp(MINI_FONT_SIZE)),
                //   ),
                // ),
                Container(
                  color: Colors.white,
                   width:ScreenUtil.getInstance().setWidth(750)-kMargin20*2,
                  padding: EdgeInsets.only(left: 10),
                  child: new Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        width: ScreenUtil.getInstance().setWidth(DP_150),
                        child: Text(
                          '支付人',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE),
                              color: black_99),
                        ),
                      ),
                      Expanded(
                        child: TextField(
                          keyboardAppearance: Brightness.light,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: black_99),
                          onChanged: (value) {
                            name = value;
                          },
                          minLines: 1,
                          cursorColor: mainColor,
                          decoration: new InputDecoration(
                              contentPadding: EdgeInsets.all(5),
                              hintText: "请填写身份证上对应的姓名",
                              border: InputBorder.none),
                        ),
                        flex: 3,
                      ),
                    ],
                  ),
                ),
                Container(
                  height: 1,
                ),
                Container(
                  width:ScreenUtil.getInstance().setWidth(750)-kMargin20*2,
                  color: Colors.white,
                  padding: EdgeInsets.only(left: 10),
                  child: new Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        width: ScreenUtil.getInstance().setWidth(DP_150),
                        child: Text(
                          '身份证号',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE),
                              color: black_99),
                        ),
                      ),
                      Expanded(
                        child: TextField(
                          keyboardAppearance: Brightness.light,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: black_99),
                          onChanged: (value) {
                            number = value;
                          },
                          minLines: 1,
                          cursorColor: mainColor,
                          decoration: new InputDecoration(
                              contentPadding: EdgeInsets.all(5),
                              hintText: "请填写身份证号",
                              border: InputBorder.none),
                        ),
                        flex: 3,
                      ),
                    ],
                  ),
                ),
                // Padding(
                //   padding:
                //       EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
                //   child: Text(
                //     '请上传真实身份证照片',
                //     style: TextStyle(
                //         color: black,
                //         fontSize:
                //             ScreenUtil.getInstance().setSp(MINI_FONT_SIZE)),
                //   ),
                // ),
                // Container(
                //   color: white,
                //   width: double.infinity,
                //   padding: EdgeInsets.all(10),
                //   child: Text(
                //     '请保证身份证清洗可见，否则无法通过审核，我们不会泄漏个人信息',
                //     style: TextStyle(
                //         color: black,
                //         fontSize:
                //             ScreenUtil.getInstance().setSp(NINIEST_FONT_SIZE)),
                //   ),
                // ),
                Container(
                  width: double.infinity,
                  color: white,
                  padding: EdgeInsets.all(10),
                  child: Row(
                    children: <Widget>[
                      Container(width: 10),
                    ],
                  ),
                ),
                new Container(
                  width: double.infinity,
                  margin:
                      EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_60)),
                  height: ScreenUtil.getInstance().setHeight(DP_60),
                  decoration: new BoxDecoration(
                      color: mainColor,
                      borderRadius: BorderRadius.circular(
                          ScreenUtil.getInstance().setHeight(DP_60))),
                  child: new FlatButton(
                    child: new Padding(
                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: new Text(
                        "提交认证",
                        style: new TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE)),
                      ),
                    ),
                    onPressed: () {
                      if (name == "" ||
                          number == ""||photo2==null||phont1==null) {
                        Fluttertoast.showToast(msg: "请填写完整信息后提交");
                        return;
                      }
                      showDialog(
                          context: context,
                          barrierDismissible: false,
                          builder: (_) {
                            return new NetLoadingDialog(
                              loadingText: "提交认证中...",
                              bgColor: Color.fromARGB(255, 0, 0, 0),
                              requestCallBack: null,
                              outsideDismiss: false,
                            );
                          });
                      up();
                    },
                  ),
                )
              ],
            ),
          ),
        ));
  }

  up() async {
    ByteData byteData = await phont1.getByteData();
    List<int> imageData = byteData.buffer.asUint8List();
    MultipartFile file =
        MultipartFile.fromBytes(imageData, filename: phont1.name);
    ByteData byteData2 = await photo2.getByteData();
    List<int> imageData2 = byteData2.buffer.asUint8List();
    MultipartFile file2 =
        MultipartFile.fromBytes(imageData2, filename: photo2.name);
                print(file2.filename);

    Map map = new Map();
    map['token'] = token;
    map['sign_type'] = createSignType(Api.URL_USER_AUTH);
    map['img_positive'] = file;
    map['img_opposite'] = file2;
    map['truename'] = name;
    map['id_num'] = number;
    Response<String> response =
        await HttpUtil().post(Api.URL_USER_AUTH, data: getSign(map));
    Map userMap = json.decode(response.data);
    Navigator.of(context).pop(1);
    if (userMap['code'] == 1 && mounted) {
      Fluttertoast.showToast(msg: "提交成功,请等待审核");
      Navigator.of(context).pop();
    } else {
      Fluttertoast.showToast(msg: userMap['msg']);
    }
  }

  Future<void> selPhoto1() async {
    List<Asset> resultList;
    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 1,
        enableCamera: true,
        materialOptions: MaterialOptions(
          actionBarTitle: "选择图片",
          allViewTitle: "已选择",
          actionBarColor: "#F1120D",
          actionBarTitleColor: "#ffffff",
          lightStatusBar: false,
          statusBarColor: "#F1120D",
          startInAllView: true,
          selectCircleStrokeColor: "#F1120D",
          selectionLimitReachedText: "已超出",
        ),
      );
    } on Exception catch (e) {
//      error = e.message;
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    if (resultList == null||resultList.length<=0) {
      return;
    }
    phont1 = resultList[0];
    setState(() {});
  }

  Future<void> selPhoto2() async {
    List<Asset> resultList;
    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 1,
        enableCamera: true,
        materialOptions: MaterialOptions(
          actionBarTitle: "选择图片",
          allViewTitle: "已选择",
          actionBarColor: "#F1120D",
          actionBarTitleColor: "#ffffff",
          lightStatusBar: false,
          statusBarColor: "#F1120D",
          startInAllView: true,
          selectCircleStrokeColor: "#F1120D",
          selectionLimitReachedText: "已超出",
        ),
      );
    } on Exception catch (e) {
//      error = e.message;
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    if (resultList == null||resultList.length<=0) {
      return;
    }
    photo2 = resultList[0];
    setState(() {});
  }
}
